// 定义 JSBridge 接口
interface JSBridge {
  sendToMini(data: Record<string, unknown>): void;
  receiveFromMini(data: Record<string, unknown>): void;
}

// 扩展 Window 接口
declare global {
  interface Window {
    Bridge: JSBridge;
    WeixinJSBridge?: {
      call: (message: { data: Record<string, unknown> }) => void;
    };
    __wxjs_environment?: string;
  }
}

// 实现 JSBridge
window.Bridge = {
  sendToMini(data: Record<string, unknown>): void {
    if (window.WeixinJSBridge) {
      alert(typeof window.WeixinJSBridge.postMessage )
      window.WeixinJSBridge.invoke({ data });
    } else if (window.__wxjs_environment === 'miniprogram') {
      // 触发小程序的 message 事件
      window.parent.postMessage({ data }, '*');
    }
  },

  // 小程序通过 evalJs 调用这个方法
  receiveFromMini(data: Record<string, unknown>): void {
    console.log('来自小程序的数据:', data);
    alert('小程序发来数据: ' + JSON.stringify(data));
  }
};

// 示例：H5 页面按钮发送数据
export const sendMsg = (data:any): void => {
  window.Bridge.sendToMini(data);
};
